package org.beetlframework.mvc.impl;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.beetl.core.GroupTemplate;
import org.beetl.ext.web.WebRender;
import org.beetlframework.BeetlContext;
import org.beetlframework.FrameworkConstant;
import org.beetlframework.mvc.UploadHelper;
import org.beetlframework.mvc.ViewResolver;
import org.beetlframework.mvc.bean.Result;
import org.beetlframework.mvc.bean.View;
import org.beetlframework.util.MapUtil;
import org.beetlframework.util.WebUtil;



/**
 * Beetl视图解析器
 *
 * @author 草原狼
 * @since 1.0
 */
public class BeetlViewResolver implements ViewResolver {
	
	private transient static final String encoding = FrameworkConstant.ENCODING;
	private transient static final String contentType = "text/html; charset=" + encoding;

	@Override
	public void resolveView(HttpServletRequest request, HttpServletResponse response, Object actionMethodResult) {
		if (actionMethodResult == null) {
			return;
		} else if (actionMethodResult instanceof View) {
			// Action 返回值若为 View，则需考虑两种视图类型（重定向 或 转发）
			View view = (View) actionMethodResult;
			processView(request, response, view);

		} else if (actionMethodResult instanceof Result) {
			// 若为 Result，则需考虑两种请求类型（文件上传 或 普通请求）
			Result result = (Result) actionMethodResult;
			processResult(request, response, result);
		} else {
			throw new RuntimeException("action方法返回值不为View或Result类型");
		}

	}
    
	/**
	 * 处理View类型结果
	 * 
	 * @param request
	 * @param response
	 * @param view
	 */
	private void processView(HttpServletRequest request, HttpServletResponse response, View view) {
		if (view.isRedirect()) {
			// 获取路径
			String path = view.getPath();
			// 重定向请求
			WebUtil.redirectRequest(path, request, response);
		} else {
			// 获取路径
			// 初始化请求属性
			Map<String, Object> data = view.getData();
			if (MapUtil.isNotEmpty(data)) {
				for (Map.Entry<String, Object> entry : data.entrySet()) {
					request.setAttribute(entry.getKey(), entry.getValue());
				}
			}
			String path = view.getPath();
			response.setContentType(contentType);
			GroupTemplate gt = BeetlContext.getGroupTemplate();
			WebRender webRender = new WebRender(gt);
			webRender.render(path, request, response);
		}

	}

	/**
	 * 处理 Result类型结果
	 * 
	 * @param request
	 * @param response
	 * @param result
	 */
	private void processResult(HttpServletRequest request, HttpServletResponse response, Result result) {
		if (UploadHelper.isMultipart(request)) {
			// 对于 multipart 类型，说明是文件上传，需要转换为 HTML 格式并写入响应中
			WebUtil.writeHTML(response, result);
		} else {
			// 对于其它类型，统一转换为 JSON 格式并写入响应中
			WebUtil.writeJSON(response, result);
		}
	}

}
